package controllers

import (
	"github.com/astaxie/beego"
	"jsk3data/models"
	"github.com/astaxie/beego/httplib"
	"github.com/labstack/gommon/log"
	"encoding/json"
	"fmt"
	"strconv"
	"io/ioutil"
	"github.com/astaxie/beego/orm"
	_ "github.com/lib/pq"
)

// Operations about object
type JsK3Controller struct {
	beego.Controller
}

// @Title Get
// @Description get user by uid
// @Param	page		path 	string	true		"page"
// @Success 200 {object} models.Rsp
// @Failure 403 :page is empty
// @router /:page [get]
func (c *JsK3Controller) Get() {
	page,_:= c.GetInt(":page",-1)
	go Jsk3(page);
	string:=strconv.Itoa(page)
	c.Data["json"] = models.Rsp{Page:string+"",Status:"START"}
	c.ServeJSON()
}


func Jsk3(page int){
	request:=httplib.Post("http://www.jslottery.com/Lottery/LotteryInfo_Fast3")
	request.Param("currentPage",strconv.Itoa(page))
	request.Param("pageSize",strconv.Itoa(200))
	rsp,err:=request.DoRequest()
	if err!=nil {
		log.Fatal(err)
	}
	 jsk3Result:=models.JSK3Data{};
	body, err := ioutil.ReadAll(rsp.Body)
	//str2 := string(body[:])
	//fmt.Println(str2)

	if err!=nil {
		log.Fatal(err)
	}
	json.Unmarshal(body,&jsk3Result)
	if err!=nil {
		log.Fatal(err)
	}
	fmt.Println(jsk3Result)
	//入库
	length:=len(jsk3Result.LotteryNumberList)
	slice := make([]models.Jsk3, length)

	for i:=0; i<length;i++  {
		jsk3Insert:=models.Jsk3{
			Issue:jsk3Result.LotteryNumberList[i].Issue,
			Ge:jsk3Result.LotteryNumberList[i].BasicNumber[0],
			Shi:jsk3Result.LotteryNumberList[i].BasicNumber[1],
			Bai:jsk3Result.LotteryNumberList[i].BasicNumber[2],
			Page:jsk3Result.Paging.CurrentPage,
		}
		slice[i]=jsk3Insert
	}
	o := orm.NewOrm()
	o.Using("default")
	o.InsertMulti(length,slice)
	//循环
	go Jsk3(jsk3Result.Paging.CurrentPage+1)
}

